<?php

/**
 *   OPENSHOP_taobao 商品相关设置
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: api_tb_goods.php,v 1.0 2009/11/5 07:35:58 add $
 *   @author      winner <jsycywm@hotmail.com>
 */

define('IN_OS', true);

require_once(dirname(__FILE__).'/includes/init.php');

require_once(ROOT_PATH . '/admin/includes/lib_goods.php');
require_once(ROOT_PATH . '/includes/modules/taobao.api/cls_api.php');
$exc = new exchange($os->table('tb_itme'),$db,'id','num_iid');
	
/* act操作项的初始化 */
if (empty($_REQUEST['act'])){
    $_REQUEST['act'] = 'list';
}else{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}

if($_REQUEST['act']=='list')
{	
	//检查权限
	admin_priv(); 
	$smarty->assign('ur_here',      '淘宝宝贝名称关联');    
	$goods_list = get_tb_goodslist();  
	$smarty->assign('goods_list',   $goods_list['goods']);
    $smarty->assign('filter',       $goods_list['filter']);
    $smarty->assign('record_count', $goods_list['record_count']);
    $smarty->assign('page_count',   $goods_list['page_count']);		 
	$smarty->assign('full_page',    1); 
    assign_query_info();    
	$smarty->display('api_tb_items_list.tpl');	 
}elseif($_REQUEST['act']=='upload_sku'){   
	$iid = $_GET['iid']   ;   
	TOP_Item_Update_SKU($iid);
}elseif($_REQUEST['act']=='item2goods'){   
	$iid = $_GET['iid']   ;     
	TOP_item2OS_goods($iid);
}elseif($_REQUEST['act']=='insert'){   
}elseif($_REQUEST['act']=='drop_color_img'){ 
}elseif($_REQUEST['act']=='edit'){ 
}elseif($_REQUEST['act']=='updata'){  
}elseif ($_REQUEST['act'] == 'remove'){ 
}elseif ($_REQUEST['act'] == 'query'){
    $goods_list = get_tb_goodslist(); 
    $smarty->assign('goods_list',   $goods_list['goods']);
    $smarty->assign('filter',       $goods_list['filter']);
    $smarty->assign('record_count', $goods_list['record_count']);
    $smarty->assign('page_count',   $goods_list['page_count']); 
    make_json_result($smarty->fetch('api_tb_items_list.tpl'), '',
     array('filter' => $goods_list['filter'], 'page_count' => $goods_list['page_count']));
}elseif($_REQUEST['act']=='relevancy'){    
	$smarty->assign('action_link',  array('href' => 'api_tb_items.php?act=list', 'text' => '淘宝宝贝关联管理'));  
	$num_iid = $_GET['num_iid']   ;     
	$tb_item_name = $db->getOne("select title from open_tb_item where num_iid='".$num_iid."'");   
	$smarty->assign('cat_goods_list',get_tb_cat_goods_list( $num_iid ));
	$smarty->assign('num_iid',$num_iid);  
	$smarty->assign('vname','['.$num_iid.']'.$tb_item_name);  
   $smarty->assign('ur_here',      '淘宝宝贝('.'['.$num_iid.']'.$tb_item_name.')关联设置' ); 
	assign_query_info();
	$smarty->display('api_tb_items_relevancy.tpl');	
} elseif ($_REQUEST['act'] == 'get_color_lib_list'){	 
}elseif($_REQUEST['act'] == 'set_default_colorlib'){  
}elseif($_REQUEST['act']=='search_cat'){   //查找关联的 
    include_once(ROOT_PATH . 'includes/cls_json.php'); 
    $json   = new JSON;
    $filter = $json->decode($_GET['JSON']);
    $filter->keyword = json_str_iconv($filter->keyword); 
    $sql = "SELECT goods_sn AS id, CONCAT('[',goods_sn,']', goods_name) as name FROM " . $os->table('goods') .
        " WHERE goods_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' or goods_sn LIKE '%" . mysql_like_quote($filter->keyword) . "%' LIMIT 50";
    
   $arr = $db->getAll($sql);
    if (empty($arr)){
        $arr = array(0 => array(
            'id'   => 0,
            'name' => '没有找到相应记录，请重新搜索'
        ));
    }

    make_json_result($arr);	
    
}elseif ($_REQUEST['act']=='add_cat_item'){ 
    include_once(ROOT_PATH . 'includes/cls_json.php');    
    $json = new JSON; 
    $goods_sn =$json->decode(  $_GET['add_ids'] );
    $goods_sn =$goods_sn[0] ; 
    $arguments  = $json->decode($_GET['JSON']);
    $num_iid   = $arguments[0]; 
	$sql = "update " . $os->table('tb_item') . " set outer_id='".$goods_sn."'where num_iid=". $num_iid; 
	$db->query($sql);  
    $arr = get_tb_cat_goods_list($num_iid );  
    $opt = array(); 
    foreach ($arr AS $val)
    {
        $opt[] = array('value'      => $val['goods_sn'],
                        'text'      => '['.$val['goods_sn'].']'.$val['goods_name'],
                        'data'      => '');
    } 
    clear_cache_files(); 
    make_json_result($opt);
    
}elseif($_REQUEST['act']=='drop_cat_item'){  
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON; 
	$goods_sn =$json->decode(  $_GET['add_ids'] );
	$goods_sn =$goods_sn[0] ; 
	$arguments  = $json->decode($_GET['JSON']);
	$num_iid   = $arguments[0]; 
	$sql = "update " . $os->table('tb_item') . " set outer_id='' where num_iid=". $num_iid;  
    $db->query($sql); 
    $arr = get_tb_cat_goods_list($num_iid);
    $opt = array(); 
    foreach ($arr AS $val){
        $opt[] = array('value'      => $val['cat_id'],
                        'text'      => $val['cat_name'],
                        'data'      => '');
    }
    
    clear_cache_files();
    make_json_result($opt);	
}

function get_tb_goodslist(){
	global $_CFG;
    $result = get_filter();
    if ($result === false)
    {
        /* 分页大小 */
        $filter = array(); 
        $filter['keyword']  = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);

        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }        
        
        if ($filter['keyword'])
        {
			$where .= " AND (tb_item.num_iid LIKE '%" . mysql_like_quote($filter['keyword']) . "%' 
						OR tb_item.title LIKE '%" . mysql_like_quote($filter['keyword']) . "%'
						OR tb_item.iid LIKE '%" . mysql_like_quote($filter['keyword']) . "%'
						OR tb_item.cid LIKE '%" . mysql_like_quote($filter['keyword']) . "%'
				        OR tb_ic.name LIKE '%" . mysql_like_quote($filter['keyword']) . "%'
						)";
        }     
                
        /* 记录总数以及页数 */
        $sql = "SELECT COUNT(*) FROM ".$GLOBALS['os']->table('tb_item')." as tb_item 
        	    left join open_tb_itemcat as tb_ic on tb_ic.cid =tb_item.cid
        		where 1 and nick='".$_CFG['taobao_user']."'  ".$where;  //仅显示当应用的商品 
        $filter['record_count'] = $GLOBALS['db']->getOne($sql); 
        $filter = page_and_size($filter); 
         /* 查询记录 */ 
		$sql = "select tb_item.num_iid, tb_item.cid,tb_ic.name as icname ,tb_item.title,tb_item.props,tb_item.property_alias,
				tb_item.seller_cids,tb_item.iid ,g.goods_name,g.goods_sn
				from open_tb_item as tb_item 
				left join open_tb_itemcat as  tb_ic on tb_item.cid =tb_ic.cid  
				left join open_goods as  g on tb_item.outer_id =g.goods_sn  where 1  and nick='".$_CFG['taobao_user']."' ".$where." ORDER BY  tb_item.id DESC";  
        /* 查询记录 */ 
        set_filter($filter, $sql); 
    }
    else{ 
        $sql    = $result['sql'];
        $filter = $result['filter'];
    } 
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);
    
    $arr = array();
    while ($rows = $GLOBALS['db']->fetchRow($res))  {   
    	$rows['props'] = Props2Name($rows['props'])  ;  
    	$rows['property_alias'] =Props_alias2name($rows['property_alias'])  ; 
        $arr[] = $rows;
    }	 
    return array('goods' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}
	
	/**
	 * 把taobao宝贝的别名换化成中文 
	 * 
	 * */
	 function Props_alias2name($property_alias){
		global  $db,$os,$topParamArr;
		$props = $property_alias;
		$str='';
		if($property_alias!=''){
			$props = explode(';', $props );  
				foreach ($props as $prop ){
					$prop = explode(':', $prop );  
					if( !is_array($prop) || !$prop[1] ) continue;
					$sql='select prop_name,name from open_tb_propvalue where vid='.$prop[1] ; 
					$row= $db->getRow($sql);
					if($row ){
						if(   $str !='' ){ 
							$str = $str.';' .$row['prop_name'] .':' .$prop[2]  ;
						} else {
							$str = $str.$row['prop_name'] .':' .$prop[2]  ;
						} 
					} 
				} 
		}  
		return $str; 
	 }

	/**
	 * 把taobao宝贝的属性转化成名称
	 * 
	 * */
	function Props2Name( $props ){
	    global  $db,$os,$topParamArr;
		$str='';
	 	$props = explode(';', $props );  
		foreach ($props as $prop ){
			$prop = explode(':', $prop );  
			if( !is_array($prop) || !$prop[1] ) continue;
			$sql='select prop_name,name from open_tb_propvalue where vid='.$prop[1] ; 
			$row= $db->getRow($sql);
			if($row ){
				if(   $str !='' ){ 
					$str = $str.';' .$row['prop_name'] .':' .$row['name']  ;
				} else {
					$str = $str.$row['prop_name'] .':' .$row['name']  ;
				} 
			} 
		} 
		return  $str;
	}



function get_tb_cat_goods_list($num_iid=0){ 
	static $rows = NULL;  
    $sql ="select tb_item.num_iid,tb_item.title,g.goods_name,g.goods_sn from open_tb_item as tb_item
 			left join open_goods as g on g.goods_sn = tb_item.outer_id "; 
	if($num_iid>0){
		$sql .= " WHERE tb_item.num_iid = '$num_iid'";
	}
	$sql .= " ORDER BY tb_item.id DESC";   
	if ($rows === NULL){
		$rows = $GLOBALS['db']->getAll($sql);
	}
	return $rows;		
}
?>